//
//  ZSGiveViewController.m
//  ROSE
//
//  Created by Apple on 2018/6/4.
//  Copyright © 2018年 HeNanZhongDunYunAn. All rights reserved.
//

#import "ZSGiveViewController.h"
#import "RoseCell.h"
#import "RoseModel.h"

@interface ZSGiveViewController ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray<RoseModel *>*myRoseArr;
@property (nonatomic,assign) NSUInteger currentPageStart;
@property (assign,nonatomic) BOOL isUp; // 是否是上拉加载
@property (weak, nonatomic) IBOutlet UILabel *showNumLabel;
@end

@implementation ZSGiveViewController
- (NSMutableArray<RoseModel *> *)myRoseArr{
    if (!_myRoseArr) {
        _myRoseArr = [NSMutableArray new];
    }
    return _myRoseArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _currentPageStart = 1;
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //设置collectionView滚动方向
    //    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //设置headerView的尺寸大小
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
    //该方法也可以设置itemSize
    //    110/150
    CGFloat width = (size_width-(15+35*2))/2;
    layout.itemSize =CGSizeMake(width, 80 + (384.0/517 * width));
    self.collectionView.collectionViewLayout = layout;
    //3.注册collectionViewCell
    //注意，此处的ReuseIdentifier 必须和 cellForItemAtIndexPath 方法中 一致 均为 cellId
    [self.collectionView registerClass:[RoseCell class] forCellWithReuseIdentifier:@"RoseCell"];
    
    //注册headerView  此处的ReuseIdentifier 必须和 supviewforsection 方法中 一致  均为reusableView
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader0"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader1"];
    [self addRefresh];
    [self loadDataWithTYPE:@"2"];// "我的玫瑰"
    self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addRefresh{
    // 下拉刷新
    NSMutableArray *headerImages = [NSMutableArray array];
    for (int i = 1; i <= 1; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"玫瑰花_selected"]];
        [headerImages addObject:image];
    }
    MJRefreshGifHeader *gifHeader = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        _isUp = NO;
        _currentPageStart = 1;
        //下拉刷新要做的操作.
        [self loadDataWithTYPE:@"2"];
    }];
    
    gifHeader.stateLabel.hidden = YES;
    gifHeader.lastUpdatedTimeLabel.hidden = YES;
    
    [gifHeader setImages:nil forState:MJRefreshStateIdle];
    [gifHeader setImages:headerImages forState:MJRefreshStateRefreshing];
    [gifHeader setImages:headerImages forState:(MJRefreshStatePulling)];
    _collectionView.mj_header = gifHeader;
    
    // 添加上拉加载
    // MJRefreshBackNormalFooter
    // MJRefreshAutoNormalFooter
    self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self.isUp = YES;// 标识上拉
        // 上拉加载时, 将当前请求的页加一
        _currentPageStart += 10;
        [self loadDataWithTYPE:@"2"];
    }];
}

- (void)loadDataWithTYPE:(NSString *)TYPE{

    NSString *urlString = [NSString stringWithFormat:@"%@/rose/myrose", url_base];
    /*
     TYPE
     String
     查询类型，必填
     1：所有者为本人的玫瑰
     2：与他人共有的玫瑰
     
     SORT
     String
     排序字段，必填
     CJSJ：创建时间
     DJ：等级
     TLZ：体力值
     
     SORTRULE
     String
     排序规则，必填
     ASC:升序
     DESC：降序
     
     start
     String
     起始行，必填，例如每页10条，第二页起始行11，第三页起始行21
     
     limt
     String
     结束行，必填，例如每页10条，第二页结束行20，第三页结束行30
     */
    
    NSUInteger limit = _currentPageStart+10;
    NSDictionary *paramDict = @{@"TYPE":TYPE,
                                @"SORT":@"CJSJ",
                                @"SORTRULE":@"DESC",
                                @"start":[NSString stringWithFormat:@"%lu", _currentPageStart],
                                @"limt":[NSString stringWithFormat:@"%lu", limit]
                                };
    [[LMJRequestManager sharedManager] POST:urlString parameters:paramDict completion:^(LMJBaseResponse *response) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        if (!response.error) {
            NSString *errorcode = [NSString stringWithFormat:@"%@", response.responseObject[@"errorcode"]];
            if ([errorcode isEqualToString:@"000000"]) {
                //
                if (_isUp) {
                    
                }else{
                    [self.myRoseArr removeAllObjects];
                }
                NSLog(@"%@", response.responseObject);
                
                NSArray *dataobj = [NSArray arrayWithArray:response.responseObject[@"dataobj"]];
                NSArray *MYROSE = dataobj;
                for (NSDictionary *temp in MYROSE) {
                    RoseModel *model = [RoseModel new];
                    [model setValuesForKeysWithDictionary:temp];
                    [self.myRoseArr addObject:model];
                }
                NSString *total = [NSString stringWithFormat:@"%@", response.responseObject[@"total"]];
                
                // 赋值
                NSString *normalString = [NSString stringWithFormat:@"共有%@支玫瑰", total];
                NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:normalString];
                [attrStr addAttribute:NSFontAttributeName value: [UIFont fontWithName: @"Papyrus" size: 13] range: NSMakeRange(0, attrStr.length)];
                NSMutableParagraphStyle * style = [[NSMutableParagraphStyle alloc] init];
                style.lineSpacing = 5.0;
                [attrStr addAttribute: NSParagraphStyleAttributeName value: style range: NSMakeRange(0, attrStr.length)];
                [attrStr addAttribute:NSForegroundColorAttributeName value:[UIColor themeColor] range:NSMakeRange(2, total.length)];
                _showNumLabel.attributedText = attrStr;
            }else{
                NSLog(@"%@[%@]", response.responseObject, errorcode);
            }
        }else{
            NSLog(@"error:%@", response.error);
        }
        [self.collectionView reloadData];
    }];
}

#pragma mark collectionView代理方法
//返回section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.myRoseArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    RoseCell *cell = (RoseCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"RoseCell" forIndexPath:indexPath];
    
    //        cell.name.text = [NSString stringWithFormat:@"{%ld,%ld}",(long)indexPath.section,(long)indexPath.row];
    //        cell.imgView.backgroundColor = [UIColor RandomColor];
    
    if (indexPath.row<self.myRoseArr.count) {
        RoseModel *model = self.myRoseArr[indexPath.row];
        [cell setDataWithRoseModel:model];
    }
    
    return cell;
}

//设置每个item的尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return CGSizeMake(90, 130);
//}

//footer的size
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(10, 10);
//}

//header的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    
    return CGSizeMake(10, 1);
}

//设置整个分区模块的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 35, 0, 35);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 15;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}


//通过设置SupplementaryViewOfKind 来设置头部或者底部的view，其中 ReuseIdentifier 的值必须和 注册是填写的一致，本例都为 “reusableView”
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    if (indexPath.section==0) {
//        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader0" forIndexPath:indexPath];
//        headerView.backgroundColor = [UIColor clearColor];
//        //        if (![headerView.subviews containsObject:indexHeaderView]) {
//        //            [headerView addSubview:indexHeaderView];
//        //        }
//        //        indexHeaderView.secHeaderLabel.text = @"我的玫瑰";
//        return headerView;
//    }else{
//        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableViewHeader1" forIndexPath:indexPath];
//
//        return headerView;
//    }
//}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RoseCell *cell = (RoseCell *)[collectionView cellForItemAtIndexPath:indexPath];
    NSString *msg = cell.name.text;
    NSLog(@"%@",msg);
}

@end
